#pragma once

#include <iostream>
#include <fstream>
#include <unordered_map>
#include <string>
#include "Log.hpp"
#include "InetAddr.hpp"

const std::string defaultdict = "./dictionary.txt";

using namespace LogModule;

class Dict
{
    const std::string sep = ": ";

public:
    Dict(const std::string &dict_path = defaultdict)
        : _dict_path(dict_path)
    {
    }

    bool LoadDict()
    {
        std::ifstream in(_dict_path);
        if (!in.is_open())
        {
            LOG(LogLevel::Error) << "打开字典" << _dict_path << "失败";
            return false;
        }

        std::string line;
        while (std::getline(in, line))
        {
            auto pos = line.find(sep);
            if (pos == std::string::npos)
            {
                LOG(LogLevel::Warning) << "解析" << line << "错误";
                continue;
            }

            std::string english = line.substr(0, pos);
            std::string chinese = line.substr(pos + sep.size());

            if (english.empty() || chinese.empty())
            {
                LOG(LogLevel::Warning) << "没有有效内容" << line;
                continue;
            }

            _dict[english] = chinese;
            LOG(LogLevel::Debug) << "加载" << line;
        }

        in.close();
        return true;
    }

    std::string Translate(const std::string &word, InetAddr &client)
    {
        auto res = _dict.find(word);
        if (res == _dict.end())
        {
            LOG(LogLevel::Debug) << "进到了翻译模块,[" << client.Ip() << " : " << client.Port() << "]#" << word << "-> None";
            return "None";
        }

        LOG(LogLevel::Debug) << "进到了翻译模块[" << client.Ip() << " : " << client.Port() << "]#" << word << "->" << res->second;
        return res->second;
    }

    ~Dict()
    {
    }

private:
    std::string _dict_path;
    std::unordered_map<std::string, std::string> _dict;
};